﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Fayshine.VA.Helpers;
using Fayshine.VA.Models;
using Fayshine.VA.RIAService.Web;
using Fayshine.VA.ViewModels;
using Visifire.Charts;
using LocalBusyIndicator = Fayshine.VA.Controls.BusyIndicator;

namespace Fayshine.VA.Views.SearchStatistics
{
    public partial class AnyDurationBuy : Page
    {
        private SearchStatisticsViewModel m_ViewModel;
        public AnyDurationBuy()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(AnyDurationBuy_Loaded);
        }

        void AnyDurationBuy_Loaded(object sender, RoutedEventArgs e)
        {
            LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
            indicator.IsBusy = true;

            this.startDatePicker.SelectedDate = DateTime.Now;
            this.endDatePicker.SelectedDate = DateTime.Now;

            m_ViewModel = new SearchStatisticsViewModel();

            m_ViewModel.AppendHistoryPassengerFlow += new AppendHistoryPassengerFlowEventHandler(m_ViewModel_AppendHistoryPassengerFlow);
            m_ViewModel.ResetHisotryChartEvent += new ResetHistoryChartEventHandler(m_ViewModel_ResetHisotryChartEvent);

            this.DataContext = m_ViewModel;
            m_ViewModel.GetAllAreas();
        }

        private void m_ViewModel_ResetHisotryChartEvent()
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                if (vcChart1 != null)
                {
                    vcChart1.AxesX.Clear();
                    vcChart1.TrendLines.Clear();
                    vcChart1.Series.Clear();
                    vcChart1.Titles.Clear();
                    vcChart1.AxesY.Clear();
                }

                if (vcChart2 != null)
                {
                    vcChart2.AxesX.Clear();
                    vcChart2.AxesY.Clear();
                    vcChart2.TrendLines.Clear();
                    vcChart2.Series.Clear();
                    vcChart2.Titles.Clear();
                }
            });
        }

        private void m_ViewModel_AppendHistoryPassengerFlow(string title, bool isIn, List<HistoryPassengerFlow> firstHistoryPassengerFlow, List<HistoryPassengerFlow> secondHistoryPassengerFlow)
        {
            this.Dispatcher.BeginInvoke(delegate()
             {
                 SetChartStatistics(GetTitleForDate() + " 客流与提袋率", firstHistoryPassengerFlow, vcChart1, true);
                 SetChartStatistics(GetTitleForDate() + " 客流与销售额", firstHistoryPassengerFlow, vcChart2, false);

                 this.dataGrid.ItemsSource = firstHistoryPassengerFlow;

                 LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                 indicator.IsBusy = false;
             });
        }

        private void SetChartStatistics(string title,List<HistoryPassengerFlow> firstHistoryPassengerFlow, Chart chart,bool isPercent)
        {
            Axis xAxis = new Axis();
            DateTime minDateTime = firstHistoryPassengerFlow.Select(s => s.HistoryTime).Min();
            DateTime maxDateTime = firstHistoryPassengerFlow.Select(s => s.HistoryTime).Max();
            xAxis.AxisMinimum = minDateTime;
            xAxis.AxisMaximum = maxDateTime;
            xAxis.ValueFormatString = "HH:mm";
            xAxis.IntervalType = IntervalTypes.Hours;
            xAxis.Interval = 1;
            chart.AxesX.Add(xAxis);

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = title;
            chart.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Column, "进人数", ChartValueTypes.Time);
            series.AxisYType = AxisTypes.Primary;
            series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
            series.DataSource = firstHistoryPassengerFlow;
            chart.Series.Add(series);

            DataSeries series2 = ChartHelper.GetDataSeries(RenderAs.Column, "成交数", ChartValueTypes.Time);
            series2.AxisYType = AxisTypes.Primary;
            series2.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            series2.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "TradeCount"));
            series2.DataSource = firstHistoryPassengerFlow;
            chart.Series.Add(series2);

            if (isPercent)
            {
                Axis syAxis = new Axis();
                syAxis.AxisType = AxisTypes.Secondary;
                syAxis.AxisMinimum = 0;
                syAxis.AxisMaximum = 1;
                syAxis.ValueFormatString = "#0.##%";
                syAxis.IntervalType = IntervalTypes.Number;
                syAxis.Interval = 0.1;
                chart.AxesY.Add(syAxis);

                DataSeries series3 = ChartHelper.GetDataSeries(RenderAs.Line, "提袋率", ChartValueTypes.Time);
                series3.AxisYType = AxisTypes.Secondary;
                series3.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
                series3.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "SalePercent"));
                series3.DataSource = firstHistoryPassengerFlow;
                chart.Series.Add(series3);
            }
            else
            {
                Axis syAxis = new Axis();
                syAxis.AxisType = AxisTypes.Secondary;
                chart.AxesY.Add(syAxis);

                DataSeries series3 = ChartHelper.GetDataSeries(RenderAs.Line, "销售额", ChartValueTypes.Time);
                series3.AxisYType = AxisTypes.Secondary;
                series3.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
                series3.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "TradeMoney"));
                series3.DataSource = firstHistoryPassengerFlow;
                chart.Series.Add(series3);
            }
        }

        private void cmbAreas_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                List<area> selectedArea = new List<area>();
                var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
                selectAreaExt.ForEach(b =>
                {
                    area temp = b.Tag as area;
                    selectedArea.Add(temp);
                });

                if (selectedArea.Count > 0)
                {
                    cbItemDisplay.Content = selectedArea.Count > 1 ? selectedArea[0].Name + "..." : selectedArea[0].Name;

                }
                else
                {
                    cbItemDisplay.Content = string.Empty;
                }
                cmbAreas.SelectedItem = null;
                cmbAreas.SelectedItem = cbItemDisplay;

                m_ViewModel.SelectAreasChanged(selectedArea);
            }
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            string msg = string.Empty;
            m_ViewModel.UpdateCheckedAreas();

            if (!FayshineManager.Instance.ValidateAreaGateInputs(m_ViewModel.CheckedAreas,
                m_ViewModel.CheckedGates, ref msg))
            {
                MessageBox.Show(msg);
            }
            else
            {
                DateTime startTime = new DateTime(startDatePicker.SelectedDate.Value.Year,
                                                  startDatePicker.SelectedDate.Value.Month,
                                                  startDatePicker.SelectedDate.Value.Day,
                                                  0, 0, 0);
                DateTime endTime = new DateTime(endDatePicker.SelectedDate.Value.Year,
                                                  startDatePicker.SelectedDate.Value.Month,
                                                  startDatePicker.SelectedDate.Value.Day,
                                                  23, 59, 59);

                if (endTime < startTime)
                {
                    MessageBox.Show("开始时间不能大于结束时间");
                }
                else
                {
                    LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                    indicator.IsBusy = true;
                    m_ViewModel.RefreshDurationPassengerAndPos(true, startTime, endTime);
                }
            }
        }

        private string GetTitleForDate()
        {
            string title = string.Empty;
            if (startDatePicker.SelectedDate.Value.Date == endDatePicker.SelectedDate.Value.Date)
            {
                title = startDatePicker.SelectedDate.Value.ToShortDateString();
            }
            else
            {
                title = startDatePicker.SelectedDate.Value.ToShortDateString() + "至" + endDatePicker.SelectedDate.Value.ToShortDateString();
            }

            m_ViewModel.AreaExtends.each(a => {

                if (a.IsSelected)
                {
                    title = title + "-" + a.Name + "-";
                }
            
            });

            return title;
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fsd = new SaveFileDialog();
            fsd.Filter = "PDF (*.pdf)|*.pdf|*PNG (*.png)|*.png";

            if (fsd.ShowDialog() == true)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                this.Dispatcher.BeginInvoke(delegate()
                {
                    FayshineManager.Instance.ExportToDisk(fsd, spContent);
                });
            }
        }

    }
}
